﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Drawing;

namespace wicDIG
{
    public class SscData : Dictionary<string, string>
    { }
    public class SscInterface
    {
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="data">Should provide following fields:
        /// Bitmap: an image file name associated with this ssc file
        /// LowerLeftUV(x,y): the coordinate of the lowerleft corner of the image
        /// UpperRightUV(x,y): the coordinate of the upperright corner of the image
        /// LocalOriginUV(x,y): local origin of rotation
        /// RotationUV: the angle or rotation in degrees
        /// </param>
        public static void Write(string filename,SscData data)
        {
            string sscText = "";
            sscText += "[SLOWSCAN]\r\n";
            sscText += "Bitmap=" + data["Bitmap"] + "\r\n";
            sscText += string.Format("LowerLeftUV={0}\r\n", new object[] { data["LowerLeftUV"]});

            sscText += string.Format("UpperRightUV={0}\r\n", new object[] { data["UpperRightUV"] });
            //the upper left corner, seems to be invalid in Elphy, but can be used here to recover transformation settings
            sscText += string.Format("LocalOriginUV={0}\r\n", new object[] { data["LocalOriginUV"]});
            //provided that the coordinate is nearly orthogonal
            sscText += "RotationUV=" + data["RotationUV"];
            
            TextWriter tw = new StreamWriter(filename);
            tw.Write(sscText);
            tw.Flush();
            tw.Close();
        }

        public static SscData Read(string filename)
        {
            TextReader tr = new StreamReader(filename);
            string sscText = tr.ReadToEnd();
            tr.Close();
            SscData data = new SscData();

            data["Bitmap"] = wicGeneral.UtilText.ReadPairedBrackets(sscText, "Bitmap=", "\r\n");
            data["LowerLeftUV"] = wicGeneral.UtilText.ReadPairedBrackets(sscText, "LowerLeftUV=", "\r\n");
            data["UpperRightUV"] = wicGeneral.UtilText.ReadPairedBrackets(sscText, "UpperRightUV=", "\r\n");
            data["LocalOriginUV"] = wicGeneral.UtilText.ReadPairedBrackets(sscText, "LocalOriginUV=", "\r\n");
            data["RotationUV"] = wicGeneral.UtilText.ReadPairedBrackets(sscText, "RotationUV=", "");

            return data;
        }

        public static PointF DataString2Point(string data)
        {
            PointF result = new PointF();
            string[] t = data.Split(new char[] {','});
            result.X = float.Parse(t[0]);
            result.Y = float.Parse(t[1]);
            return result;
        }
        public static string Point2DataString(PointF point)
        {
            return string.Format("{0},{1}", new object[] { point.X, point.Y });
        }
        

    }
}
